import java.util.Arrays;

public class MyArrayList {
    public int[] elem;
    public int usedSize;//0
    //默认容量
    private static final int DEFAULT_SIZE = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }
    public void display(){
        if (usedSize > 0){
            System.out.println(Arrays.toString(elem));
        }
    }

    public void add(int data){
       if (isFull()){
           elem = Arrays.copyOf(elem,2*elem.length);
       }
        elem[usedSize] = data;
        usedSize++;
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    private boolean isEmpty() {
        return this.usedSize == 0;
    }

    private boolean checkPosInAdd(int pos) {
        if(pos < 0 || pos > this.usedSize) {
            System.out.println("pos位置不合法");
            return false;
        }
        return true;//合法
    }

    public void add(int pos,int data) throws MyArrayListIndexOutOfException {
        if (!checkPosInAdd(pos)){
            throw new MyArrayListIndexOutOfException("pos位置不合法");
        }
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        for (int i = usedSize-1; i >= pos; i--) {
            elem[i+1] = elem[i];
        }elem[pos] = data;
        usedSize++;
    }
    public boolean contains(int toFind){
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == toFind){
                return true;
            }
        }return false;
    }

    public int indexOf(int toFind){
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == toFind){
                return i;
            }
        }return -1;
    }

    public int get(int pos) throws MyArrayListIndexOutOfException, MyArrayListEmptyException {
        if (isEmpty()){
            throw new MyArrayListEmptyException("该顺序表为空");
        }
        if (!checkPosInAdd(pos)){
            throw new MyArrayListIndexOutOfException("pos位置不合法");
        }
        return elem[pos];
    }

    public void set(int pos,int value) throws MyArrayListEmptyException, MyArrayListIndexOutOfException {
        if (isEmpty()){
            throw new MyArrayListEmptyException("该顺序表为空");
        }
        if (!checkPosInAdd(pos)){
            throw new MyArrayListIndexOutOfException("pos位置不合法");
        }
        elem[pos] = value;
    }

    public void remove(int key) throws MyArrayListEmptyException {
        if(isEmpty()) {
            throw new MyArrayListEmptyException("顺序表为空，不能删除！");
        }
        int index = indexOf(key);
        if(index == -1) {
            System.out.println("不存在你要删除的数据");
            return;
        }
        for (int i = index; i < this.usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize--;
    }

    public void clear(){
        elem = null;
    }

    public int size() {
        return this.usedSize;
    }
}
